package com.sls.web.manager.action.recharge;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Value;

import com.sls.web.manager.action.SuperAction;
import com.sls.web.manager.common.Constants;
import com.sls.web.manager.common.WebTools;
import com.sls.web.manager.page.Pagination;
import com.sls.web.manager.pojo.UserInfoVO;
import com.sls.web.manager.recharge.pojo.CardImportLog;
import com.sls.web.manager.recharge.pojo.CardInfo;
import com.sls.web.manager.recharge.pojo.SystemProduct;
import com.sls.web.manager.recharge.querybean.CardImportLogQuery;
import com.sls.web.manager.recharge.querybean.CardInfoQuery;
import com.sls.web.manager.recharge.querybean.SystemProductQuery;
import com.sls.web.manager.recharge.service.CardImportLogService;
import com.sls.web.manager.recharge.service.CardInfoService;
import com.sls.web.manager.recharge.service.SystemProductService;

@Results(value = { @Result(name = "filedownload", type = "stream", params = {
		"contentType", "application/x-download", "inputName", "istream",
		"contentDisposition", "attachment;filename=${fileName}" }) })
public class CardInfoAction extends SuperAction {
	private static final long serialVersionUID = 6524626317742577395L;

	@Resource(name = "cardInfoService")
	private CardInfoService cardInfoService;

	@Resource(name = "cardImportLogService")
	private CardImportLogService cardImportLogService;

	@Resource(name = "systemProductService")
	private SystemProductService systemProductService;
	// 页面使用
	private Pagination<CardInfo> page;
	private String startdate;// 销售 开始日期
	private String enddate;// 销售 结束日期
	private CardInfoQuery cardInfoQuery;
	private String cardName;

	private SystemProductQuery systemProductQuery;
	private String systemProductId;

	private String importDate;// 导入时间
	private String cardSerial;// 卡号
	private String cardBatchNo;// 导入批次号
	private String importStartDate;// 导入开始日期
	private String importEndDate;// 导入结束日期
	private String returnCardStartDate;// 退卡开始日期
	private String returnCardEndDate;// 退卡结束日期
	private String cardStatus;// 卡密状态
	private String usStatus;// 是否启用

	// 下载使用
	// @Value("${file.create.temp.dir}")
	private String baseDir;
	@Value("${file.server.ip}")
	private String fileServerIp;
	@Value("${file.server.port}")
	private String fileServerPort;
	@Value("${file.client}")
	private String fileClient;

	private String fileName;// 文件名称
	private InputStream istream; // 输入流

	// 禁用页面使用
	private String cardId;

	/**
	 * 展示卡密信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		UserInfoVO userInfoVO = getCurrentOperator();
		SystemProduct sp = null;
		if (StringUtils.isNotBlank(systemProductId)) {
			systemProductQuery = new SystemProductQuery();
			systemProductQuery.setId(systemProductId);
			sp = systemProductService.queryOne(systemProductQuery, userInfoVO);
		}
		if (sp != null) {
			cardName = sp.getName();
		}

		// 查询cardInfo
		if (cardInfoQuery == null) {
			cardInfoQuery = new CardInfoQuery();
			cardInfoQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
			cardInfoQuery.setPageSize(Constants.INIT_PAGESIZE);
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Date d = new Date();

		if (StringUtils.isBlank(importStartDate)) {
			importStartDate = sdf.format(DateAgeOfMonth(d, -1));
		}
		if (StringUtils.isBlank(importEndDate)) {
			importEndDate = sdf.format(d);
		}

		cardInfoQuery.setImportStartDate(importStartDate);
		cardInfoQuery.setImportEndDate(importEndDate);
		cardInfoQuery.setCardName(cardName);

		if (StringUtils.isNotBlank(usStatus)) {
			if ("0".equals(usStatus)) {
				cardInfoQuery.setEnable(false);
			} else if ("1".equals(usStatus)) {
				cardInfoQuery.setEnable(true);
			}
		}

		if (StringUtils.isNotBlank(cardStatus)) {
			try {
				cardInfoQuery.setStatus(Integer.parseInt(cardStatus));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isNotBlank(cardSerial)) {
			cardInfoQuery.setCardSerial(cardSerial);
		}
		if (StringUtils.isNotBlank(cardBatchNo)) {
			cardInfoQuery.setCardImportBatchNum(cardBatchNo);
		}
		page = cardInfoService.queryCardInfoPage(cardInfoQuery, userInfoVO);
		if (page != null && page.getList() != null && !page.getList().isEmpty()) {
			StringBuilder sb = new StringBuilder();
			for (CardInfo info : page.getList()) {
				String password = info.getCardPassword();
				if (password != null) {
					char[] cha = password.toCharArray();
					for (int i = 0; i < cha.length; i++) {
						if (i < 4 || (cha.length - i - 1) < 4) {
							sb.append(cha[i]);
						} else if (sb.indexOf("**") == -1) {
							sb.append("********");
						}
					}
					info.setCardPassword(sb.toString());
					sb.delete(0, sb.length());
				}
			}
		}
		return "list";
	}

	/**
	 * 批量操作
	 * 
	 * @return
	 * @throws Exception
	 */
	public String toBatchOperate() throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		importDate = sdf.format(new Date());
		return "batch";
	}

	/**
	 * 查找导入批次号
	 * 
	 * @return
	 * @throws Exception
	 */
	public String queryImportBatch() throws Exception {
		List<String> result = new ArrayList<String>();
		if (StringUtils.isNotBlank(importDate)) {
			CardImportLogQuery query = new CardImportLogQuery();
			query.setImportStartDate(importDate);
			query.setImportEndDate(importDate);
			List<CardImportLog> list = cardImportLogService.queryList(query,
					getCurrentOperator());
			if (list != null && !list.isEmpty()) {
				for (CardImportLog cardImportLog : list) {
					result.add(cardImportLog.getCardBatchNum());
				}
			}
		}
		// writeAjax(result);
		message = WebTools.writeAjax(result);
		return "ajax";
	}

	/**
	 * 按批次操作
	 * 
	 * @return
	 * @throws Exception
	 */
	public String updateByImportBatchNum() throws Exception {
		String enable = (String) WebTools.getParameter("enable");// 是否启用,禁用
		String backcard = (String) WebTools.getParameter("backcard");// 退卡
		String useLevel = (String) WebTools.getParameter("useLevel");// 退卡
		// 以下字段必传
		String importBatchNum = (String) WebTools
				.getParameter("importBatchNum");// 导入批次号()
		String functionno = (String) WebTools.getParameter("functionno");// 功能号(1,启用和禁用;2,退卡;3,设置优先级)
		String result = "";
		if (StringUtils.isNotBlank(importBatchNum)
				&& StringUtils.isNotBlank(functionno)) {
			CardInfo info = new CardInfo();
			info.setCardImportBatchNum(importBatchNum);
			if ("1".equals(functionno)) {
				// 启用禁用
				Boolean bool = null;
				if ("1".equals(enable)) {
					bool = true;
				} else if ("0".equals(enable)) {
					bool = false;
				}
				info.setEnable(bool);
			} else if ("2".equals(functionno)) {
				// 退卡
				if ("true".equals(backcard)) {
					info.setStatus(4);// 退卡
				}
			} else if ("3".equals(functionno)) {
				// 设置优先级
				if (StringUtils.isNotBlank(useLevel)) {
					info.setUseLevel(Integer.valueOf(useLevel));// 退卡
				}
			}
			boolean opt = cardInfoService.updateCardInfoByImportBatchNum(info,
					getCurrentOperator());
			result = opt ? "success" : "error";
		}
		// writeAjax(result);
		message = result;
		return "ajax";
	}

	/**
	 * 导出卡密信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String export() throws Exception {
		if (cardInfoQuery == null) {
			cardInfoQuery = new CardInfoQuery();
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		Date d = new Date();
		if (StringUtils.isBlank(importStartDate)) {
			importStartDate = sdf.format(DateAgeOfMonth(d, -1));
		}
		if (StringUtils.isBlank(importEndDate)) {
			importEndDate = sdf.format(d);
		}

		cardInfoQuery.setImportStartDate(importStartDate);
		cardInfoQuery.setImportEndDate(importEndDate);
		cardInfoQuery.setCardName(cardName);

		String importBatchNum = (String) WebTools
				.getParameter("importBatchNum");// 导入批次号()
		if (StringUtils.isNotBlank(importBatchNum)) {
			cardInfoQuery.setCardImportBatchNum(importBatchNum);
		}
		if (StringUtils.isNotBlank(usStatus)) {
			if ("0".equals(usStatus)) {
				cardInfoQuery.setEnable(false);
			} else if ("1".equals(usStatus)) {
				cardInfoQuery.setEnable(true);
			}
		}

		if (StringUtils.isNotBlank(cardStatus)) {
			try {
				cardInfoQuery.setStatus(Integer.parseInt(cardStatus));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		String useLevel = (String) WebTools.getParameter("useLevel");// 使用等级
		if (StringUtils.isNotBlank(useLevel)) {
			try {
				cardInfoQuery.setUseLevel(Integer.valueOf(useLevel));
			} catch (Exception e) {
			}
		}
		if (StringUtils.isNotBlank(importDate)) {
			cardInfoQuery.setImportStartDate(importDate);
			cardInfoQuery.setImportEndDate(importDate);
		}

		String fileType = WebTools.getParameter("fileType");// 文件导出类型
		if (StringUtils.isBlank(fileType)) {
			fileType = "txt";
		}
		cardInfoQuery.setExportFileType(fileType);
		String filename = cardInfoService.createCardInfoFileTxt(cardInfoQuery,
				getCurrentOperator());
		if (StringUtils.isNotBlank(filename)) {

			// String filename = "20121106144838593_165.txt";

			String saleStatusStr = "";
			if (cardInfoQuery.getStatus() != null) {
				int saleStatus = cardInfoQuery.getStatus();
				if (saleStatus == 0) {
					saleStatusStr = "待销售_";
				} else if (saleStatus == 1) {
					saleStatusStr = "已销售_";
				}
			}

			String filenameWeb = "卡密信息_" + saleStatusStr + filename;
			// 获取文件下载路径
			URL url = Thread.currentThread().getContextClassLoader()
					.getResource("");
			URI uri = new URI(url.toURI().toString() + "download");
			File dir = new File(uri);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			baseDir = dir.getAbsolutePath();
			String filePath = baseDir + "/" + filename;
			getFileFormServer(filePath, filename);
			downloadfile(filePath, filenameWeb);
			return "filedownload";
		}
		return null;
	}

	/**
	 * @param filePath
	 *            文件路径
	 * @param filenameWeb
	 *            返回页面的文件名
	 * @throws Exception
	 */
	public void downloadfile(String filePath, String filenameWeb)
			throws Exception {
		fileName = new String(filenameWeb.getBytes("GBK"), "iso8859-1");
		File file = new File(filePath);
		if (!file.exists()) {
			return;
		}
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] tempbytes = new byte[1024];
		int byteread = 0;
		// 读入多个字节到字节数组中，byteread为一次读入的字节数
		while ((byteread = fis.read(tempbytes)) != -1) {
			baos.write(tempbytes, 0, byteread);
		}
		fis.close();
		if (file.exists()) {
			file.delete();
		}
		istream = new ByteArrayInputStream(baos.toByteArray());
	}

	/**
	 * 卡密修改
	 * 
	 * @return
	 * @throws Exception
	 */
	public String modifyCard() throws Exception {
		CardInfoQuery query = new CardInfoQuery();
		if (StringUtils.isNotBlank(cardId)) {
			query.setCardId(cardId);
		}

		List<CardInfo> list = cardInfoService.queryCardInfo(query,
				getCurrentOperator());
		String result = "";
		if (list != null && !list.isEmpty()) {
			CardInfo info = list.get(0);
			info.setEnable(!info.getEnable());
			boolean bool = cardInfoService.updateCardInfo(info,
					getCurrentOperator());
			result = bool ? "success" : "error";
		}
		// writeAjax(result);
		message = WebTools.writeAjax(result);
		return "ajax";
	}

	public Date DateAgeOfMonth(Date d, int month) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(d);
		cal.add(Calendar.MONTH, month);
		return cal.getTime();
	}

	/**
	 * 从文件服务器获取文件
	 * 
	 * @param filePath
	 *            文件全路径名
	 * @param fileName
	 *            文件名
	 */
	private void getFileFormServer(final String filePath, String fileName) {
		String cmdStr = "";
		String os = getOS();
		if (os.contains("Windows")) {
			cmdStr = "cmd /c " + fileClient + " get " + filePath + " "
					+ fileName + " " + fileServerIp + " " + fileServerPort;
		} else if (os.contains("Linux")) {
			cmdStr = fileClient + " get " + filePath + " " + fileName + " "
					+ fileServerIp + " " + fileServerPort;
		}
		final String cmd = cmdStr;

		Process p = null;
		try {
			p = Runtime.getRuntime().exec(cmd);
			int i = p.waitFor();// 挂起等待
			if (i != 0) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						p.getInputStream()));
				String line = null;
				while ((line = br.readLine()) != null) {
					log.info(line);
				}

				br = new BufferedReader(new InputStreamReader(
						p.getErrorStream(), "UTF-8"));
				line = null;
				while ((line = br.readLine()) != null) {
					log.info(line);
				}
			} else {
				File file = new File(filePath);
				if (file.exists()) {
					// file.delete();
				}
			}
			if (p != null) {
				p.destroy();
				p = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 判断操作系统
	 * 
	 * @return
	 */
	private String getOS() {
		String os = "";
		if ("\\".equals(File.separator)) {
			os = "Windows";
		} else if ("/".equals(File.separator)) {
			os = "Linux";
		}
		return os;
	}

	public Pagination<CardInfo> getPage() {
		return page;
	}

	public void setPage(Pagination<CardInfo> page) {
		this.page = page;
	}

	public String getStartdate() {
		return startdate;
	}

	public void setStartdate(String startdate) {
		this.startdate = startdate;
	}

	public String getEnddate() {
		return enddate;
	}

	public void setEnddate(String enddate) {
		this.enddate = enddate;
	}

	public CardInfoQuery getCardInfoQuery() {
		return cardInfoQuery;
	}

	public void setCardInfoQuery(CardInfoQuery cardInfoQuery) {
		this.cardInfoQuery = cardInfoQuery;
	}

	public String getCardName() {
		return cardName;
	}

	public void setCardName(String cardName) {
		this.cardName = cardName;
	}

	public String getImportStartDate() {
		return importStartDate;
	}

	public void setImportStartDate(String importStartDate) {
		this.importStartDate = importStartDate;
	}

	public String getImportEndDate() {
		return importEndDate;
	}

	public void setImportEndDate(String importEndDate) {
		this.importEndDate = importEndDate;
	}

	public String getReturnCardStartDate() {
		return returnCardStartDate;
	}

	public void setReturnCardStartDate(String returnCardStartDate) {
		this.returnCardStartDate = returnCardStartDate;
	}

	public String getReturnCardEndDate() {
		return returnCardEndDate;
	}

	public void setReturnCardEndDate(String returnCardEndDate) {
		this.returnCardEndDate = returnCardEndDate;
	}

	public String getCardStatus() {
		return cardStatus;
	}

	public void setCardStatus(String cardStatus) {
		this.cardStatus = cardStatus;
	}

	public String getUsStatus() {
		return usStatus;
	}

	public void setUsStatus(String usStatus) {
		this.usStatus = usStatus;
	}

	public String getCardId() {
		return cardId;
	}

	public void setCardId(String cardId) {
		this.cardId = cardId;
	}

	public String getCardSerial() {
		return cardSerial;
	}

	public void setCardSerial(String cardSerial) {
		this.cardSerial = cardSerial;
	}

	public String getCardBatchNo() {
		return cardBatchNo;
	}

	public void setCardBatchNo(String cardBatchNo) {
		this.cardBatchNo = cardBatchNo;
	}

	public String getImportDate() {
		return importDate;
	}

	public void setImportDate(String importDate) {
		this.importDate = importDate;
	}

	public String getSystemProductId() {
		return systemProductId;
	}

	public void setSystemProductId(String systemProductId) {
		this.systemProductId = systemProductId;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public InputStream getIstream() {
		return istream;
	}

	public void setIstream(InputStream istream) {
		this.istream = istream;
	}

}
